using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using SQLRunner;
using SqlRunner.controls;
using SqlRunner.Readers;
using SqlRunner.UserInterfaceStatus;
using SQLRunnerLib.DB;
using SQLRunnerLib.Project;
using SQLRunnerLib.Services;
using SQLRunnerLib.Util;
using SQLRunnerLib.VersionCheck;
using SQLServices.Log;
using SQLServices.TransMgr;

namespace SqlRunner
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class FormMain : Form
	{
		#region Private Members

		#region Controls

		private FolderBrowserDialog fBrowser;
		private StatusBar stsBar;
		private StatusBarPanel txtComment;
		private StatusBarPanel txtTotal;
		private StatusBarPanel txtTotalErrors;
		private StatusBarPanel txtElapsedTime;
		private Label label1;
		private GroupBox grpDB;
		private GroupBox grpUser;
		private TextBox txtPwd;
		private Label label3;
		private TextBox txtUser;
		private Label label2;
		private CheckBox chkTrusted;
		private GroupBox grpLogin;
		private Button btOpenDB;
		private ComboBox cmbDatabases;
		private Label label4;
		private Button btnConn;
		private GroupBox grpSQLPath;
		private Button btnFolder;
		private GroupBox grpRun;
		private Button btnRun;
		private GroupBox grpScriptList;
		private TreeView treeScripts;
		private Button btnClear;
		private MainMenu mnuMain;
		private MenuItem mnuFile;
		private MenuItem mnuReset;
		private MenuItem menuItem3;
		private MenuItem mnuExit;
		private IContainer components;

		private CheckedListBox lstFolders;
		private Button btnRemove;
		private Button btnClearFolders;
		private Button btnUp;
		private Button btnDown;

		private ToolTip toolTip;
		private CheckBox chkSubFolders;
		private GroupBox grpEvent;
		private Button btnSQL;
		private TextBox txtEventError;
		private TextBox txtEventName;
		private Panel progressPane;
		private PictureBox progressPict;
		private ProgressBar progressBar;
		private readonly TimerExtended timerExecution;
		private ComboBox cmbServer;
		private MenuItem menuItem1;
		private MenuItem menuItem2;
		private Button btnAbort;
		private MenuItem mnuOpen;
		private MenuItem mnuSave;
		private MenuItem mnuSaveAs;
		private MenuItem menuItem6;
		private OpenFileDialog openFile;
		private SaveFileDialog saveFile;

		#endregion

		#region Private Instances

		static frmSplash splashForm;
		static frmCheckNewVersion checkVersionForm;
		private RunnerSettings AppSettings;
		private int errorCounter = 0;
		private int totalCounter = 0;

		private Status applicationStatus = Status.Initial;
		private readonly Groups applicationGroups = new Groups();
		private Status projectStatus = Status.Initial;
		private Status prevFolderStatus = Status.Initial;
		private readonly Groups folderGroups = new Groups();
		private readonly FormMainController controller;

		#endregion

		#region Icons
		// TODO: Load icons from resource file or something similar
		private readonly Icon I_FOLDER = new Icon(Path.Combine(Application.StartupPath, @"images\folder.ico"));
		private readonly Icon I_FOLDER_C = new Icon(Path.Combine(Application.StartupPath,@"images\folder_cancelled.ico"));
		private readonly Icon I_FOLDER_OPEN = new Icon(Path.Combine(Application.StartupPath, @"images\folder_open.ico"));
		private readonly Icon I_FOLDER_OPEN_C = new Icon(Path.Combine(Application.StartupPath,@"images\folder_open_cancelled.ico"));
		private readonly Icon I_FILE = new Icon(Path.Combine(Application.StartupPath,@"images\sqlfile.ico"));
		private MenuItem mnuNew;
        private MenuItem mnuConnMgr;
        private MenuItem mnuOptimisticMgr;
        private MenuItem mnuPessimisticMgr;
        private MenuItem mnuStrictMgr;
        private MenuItem mnuCommitMgr;
        private MenuItem mnuRollbackMgr;
        private StatusBarPanel txtConnMgrMode;
        private Button bntSearch;
		private readonly Icon I_FILE_C = new Icon(Path.Combine(Application.StartupPath,@"images\sqlfile_cancelled.ico"));
		

		#endregion
		
		private enum IconList
		{
			Folder = 0,
			Folder_Cancelled = 1,
			File = 2,
			File_Cancelled = 3,
			Folder_Open = 4,
			Folder_Open_Cancelled = 5
		}

		#endregion
		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain));
            this.fBrowser = new System.Windows.Forms.FolderBrowserDialog();
            this.grpDB = new System.Windows.Forms.GroupBox();
            this.label4 = new System.Windows.Forms.Label();
            this.cmbDatabases = new System.Windows.Forms.ComboBox();
            this.btOpenDB = new System.Windows.Forms.Button();
            this.stsBar = new System.Windows.Forms.StatusBar();
            this.txtComment = new System.Windows.Forms.StatusBarPanel();
            this.txtConnMgrMode = new System.Windows.Forms.StatusBarPanel();
            this.txtTotal = new System.Windows.Forms.StatusBarPanel();
            this.txtTotalErrors = new System.Windows.Forms.StatusBarPanel();
            this.txtElapsedTime = new System.Windows.Forms.StatusBarPanel();
            this.grpLogin = new System.Windows.Forms.GroupBox();
            this.cmbServer = new System.Windows.Forms.ComboBox();
            this.btnConn = new System.Windows.Forms.Button();
            this.chkTrusted = new System.Windows.Forms.CheckBox();
            this.grpUser = new System.Windows.Forms.GroupBox();
            this.txtPwd = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.txtUser = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.grpSQLPath = new System.Windows.Forms.GroupBox();
            this.btnDown = new System.Windows.Forms.Button();
            this.btnUp = new System.Windows.Forms.Button();
            this.btnClearFolders = new System.Windows.Forms.Button();
            this.btnRemove = new System.Windows.Forms.Button();
            this.lstFolders = new System.Windows.Forms.CheckedListBox();
            this.btnFolder = new System.Windows.Forms.Button();
            this.chkSubFolders = new System.Windows.Forms.CheckBox();
            this.grpRun = new System.Windows.Forms.GroupBox();
            this.progressPane = new System.Windows.Forms.Panel();
            this.btnAbort = new System.Windows.Forms.Button();
            this.progressBar = new System.Windows.Forms.ProgressBar();
            this.progressPict = new System.Windows.Forms.PictureBox();
            this.btnRun = new System.Windows.Forms.Button();
            this.grpScriptList = new System.Windows.Forms.GroupBox();
            this.btnClear = new System.Windows.Forms.Button();
            this.treeScripts = new System.Windows.Forms.TreeView();
            this.mnuMain = new System.Windows.Forms.MainMenu(this.components);
            this.mnuFile = new System.Windows.Forms.MenuItem();
            this.mnuNew = new System.Windows.Forms.MenuItem();
            this.mnuOpen = new System.Windows.Forms.MenuItem();
            this.mnuSave = new System.Windows.Forms.MenuItem();
            this.mnuSaveAs = new System.Windows.Forms.MenuItem();
            this.menuItem6 = new System.Windows.Forms.MenuItem();
            this.mnuReset = new System.Windows.Forms.MenuItem();
            this.menuItem3 = new System.Windows.Forms.MenuItem();
            this.mnuExit = new System.Windows.Forms.MenuItem();
            this.mnuConnMgr = new System.Windows.Forms.MenuItem();
            this.mnuOptimisticMgr = new System.Windows.Forms.MenuItem();
            this.mnuPessimisticMgr = new System.Windows.Forms.MenuItem();
            this.mnuStrictMgr = new System.Windows.Forms.MenuItem();
            this.mnuCommitMgr = new System.Windows.Forms.MenuItem();
            this.mnuRollbackMgr = new System.Windows.Forms.MenuItem();
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.menuItem2 = new System.Windows.Forms.MenuItem();
            this.toolTip = new System.Windows.Forms.ToolTip(this.components);
            this.btnSQL = new System.Windows.Forms.Button();
            this.grpEvent = new System.Windows.Forms.GroupBox();
            this.txtEventError = new System.Windows.Forms.TextBox();
            this.txtEventName = new System.Windows.Forms.TextBox();
            this.openFile = new System.Windows.Forms.OpenFileDialog();
            this.saveFile = new System.Windows.Forms.SaveFileDialog();
            this.bntSearch = new System.Windows.Forms.Button();
            this.grpDB.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.txtComment)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtConnMgrMode)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtTotal)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtTotalErrors)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtElapsedTime)).BeginInit();
            this.grpLogin.SuspendLayout();
            this.grpUser.SuspendLayout();
            this.grpSQLPath.SuspendLayout();
            this.grpRun.SuspendLayout();
            this.progressPane.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.progressPict)).BeginInit();
            this.grpScriptList.SuspendLayout();
            this.grpEvent.SuspendLayout();
            this.SuspendLayout();
            // 
            // fBrowser
            // 
            this.fBrowser.Description = "Select folder to run SQL scripts from";
            this.fBrowser.ShowNewFolderButton = false;
            // 
            // grpDB
            // 
            this.grpDB.Controls.Add(this.label4);
            this.grpDB.Controls.Add(this.cmbDatabases);
            this.grpDB.Controls.Add(this.btOpenDB);
            this.grpDB.Dock = System.Windows.Forms.DockStyle.Top;
            this.grpDB.Enabled = false;
            this.grpDB.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.grpDB.Location = new System.Drawing.Point(0, 96);
            this.grpDB.Name = "grpDB";
            this.grpDB.Size = new System.Drawing.Size(608, 56);
            this.grpDB.TabIndex = 2;
            this.grpDB.TabStop = false;
            this.grpDB.Text = "SQL Database";
            // 
            // label4
            // 
            this.label4.Location = new System.Drawing.Point(8, 24);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(96, 24);
            this.label4.TabIndex = 15;
            this.label4.Text = "&DB name:";
            // 
            // cmbDatabases
            // 
            this.cmbDatabases.AccessibleDescription = "hrooo";
            this.cmbDatabases.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbDatabases.Location = new System.Drawing.Point(104, 24);
            this.cmbDatabases.Name = "cmbDatabases";
            this.cmbDatabases.Size = new System.Drawing.Size(208, 21);
            this.cmbDatabases.TabIndex = 14;
            this.toolTip.SetToolTip(this.cmbDatabases, "Select the database to run the scripts");
            // 
            // btOpenDB
            // 
            this.btOpenDB.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.btOpenDB.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btOpenDB.Location = new System.Drawing.Point(472, 24);
            this.btOpenDB.Name = "btOpenDB";
            this.btOpenDB.Size = new System.Drawing.Size(128, 24);
            this.btOpenDB.TabIndex = 13;
            this.btOpenDB.Text = "&Open Database";
            this.toolTip.SetToolTip(this.btOpenDB, "Selects the database to run the scripts and allows to select the folders where to" +
                    " find the SQL scripts");
            this.btOpenDB.Click += new System.EventHandler(this.btOpenDB_Click);
            // 
            // stsBar
            // 
            this.stsBar.Location = new System.Drawing.Point(0, 461);
            this.stsBar.Name = "stsBar";
            this.stsBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
            this.txtComment,
            this.txtConnMgrMode,
            this.txtTotal,
            this.txtTotalErrors,
            this.txtElapsedTime});
            this.stsBar.ShowPanels = true;
            this.stsBar.Size = new System.Drawing.Size(608, 16);
            this.stsBar.TabIndex = 4;
            this.stsBar.Text = "statusBar1";
            // 
            // txtComment
            // 
            this.txtComment.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
            this.txtComment.Name = "txtComment";
            this.txtComment.Text = "Idle";
            this.txtComment.Width = 380;
            // 
            // txtConnMgrMode
            // 
            this.txtConnMgrMode.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents;
            this.txtConnMgrMode.Name = "txtConnMgrMode";
            this.txtConnMgrMode.Text = "Connection Manager: Pessimistic";
            this.txtConnMgrMode.Width = 182;
            // 
            // txtTotal
            // 
            this.txtTotal.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents;
            this.txtTotal.Name = "txtTotal";
            this.txtTotal.Width = 10;
            // 
            // txtTotalErrors
            // 
            this.txtTotalErrors.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents;
            this.txtTotalErrors.Name = "txtTotalErrors";
            this.txtTotalErrors.Width = 10;
            // 
            // txtElapsedTime
            // 
            this.txtElapsedTime.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents;
            this.txtElapsedTime.Name = "txtElapsedTime";
            this.txtElapsedTime.Width = 10;
            // 
            // grpLogin
            // 
            this.grpLogin.Controls.Add(this.cmbServer);
            this.grpLogin.Controls.Add(this.bntSearch);
            this.grpLogin.Controls.Add(this.btnConn);
            this.grpLogin.Controls.Add(this.chkTrusted);
            this.grpLogin.Controls.Add(this.grpUser);
            this.grpLogin.Controls.Add(this.label1);
            this.grpLogin.Dock = System.Windows.Forms.DockStyle.Top;
            this.grpLogin.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.grpLogin.Location = new System.Drawing.Point(0, 0);
            this.grpLogin.Name = "grpLogin";
            this.grpLogin.Size = new System.Drawing.Size(608, 96);
            this.grpLogin.TabIndex = 4;
            this.grpLogin.TabStop = false;
            this.grpLogin.Text = "SQL Server";
            // 
            // cmbServer
            // 
            this.cmbServer.Location = new System.Drawing.Point(104, 24);
            this.cmbServer.Name = "cmbServer";
            this.cmbServer.Size = new System.Drawing.Size(168, 21);
            this.cmbServer.TabIndex = 3;
            this.cmbServer.Text = "localhost";
            this.toolTip.SetToolTip(this.cmbServer, "Enter here the SQL Server instance name");
            // 
            // btnConn
            // 
            this.btnConn.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.btnConn.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnConn.Location = new System.Drawing.Point(472, 24);
            this.btnConn.Name = "btnConn";
            this.btnConn.Size = new System.Drawing.Size(128, 24);
            this.btnConn.TabIndex = 11;
            this.btnConn.Text = "&Connect to SQL Server";
            this.toolTip.SetToolTip(this.btnConn, "Connects to selected SQL Server");
            this.btnConn.Click += new System.EventHandler(this.btnConn_Click);
            // 
            // chkTrusted
            // 
            this.chkTrusted.Checked = true;
            this.chkTrusted.CheckState = System.Windows.Forms.CheckState.Checked;
            this.chkTrusted.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.chkTrusted.Location = new System.Drawing.Point(8, 64);
            this.chkTrusted.Name = "chkTrusted";
            this.chkTrusted.Size = new System.Drawing.Size(232, 16);
            this.chkTrusted.TabIndex = 6;
            this.chkTrusted.Text = "Trusted Connection";
            this.toolTip.SetToolTip(this.chkTrusted, "If selected it uses the Authenticated Windows user name to connect to the SQL Ser" +
                    "ver");
            this.chkTrusted.CheckedChanged += new System.EventHandler(this.chkTrusted_CheckedChanged);
            // 
            // grpUser
            // 
            this.grpUser.Controls.Add(this.txtPwd);
            this.grpUser.Controls.Add(this.label3);
            this.grpUser.Controls.Add(this.txtUser);
            this.grpUser.Controls.Add(this.label2);
            this.grpUser.Enabled = false;
            this.grpUser.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.grpUser.Location = new System.Drawing.Point(280, 16);
            this.grpUser.Name = "grpUser";
            this.grpUser.Size = new System.Drawing.Size(184, 72);
            this.grpUser.TabIndex = 10;
            this.grpUser.TabStop = false;
            this.grpUser.Text = "User details";
            // 
            // txtPwd
            // 
            this.txtPwd.Location = new System.Drawing.Point(72, 44);
            this.txtPwd.Name = "txtPwd";
            this.txtPwd.PasswordChar = '*';
            this.txtPwd.Size = new System.Drawing.Size(104, 20);
            this.txtPwd.TabIndex = 10;
            this.toolTip.SetToolTip(this.txtPwd, "Password for selected SQL user");
            // 
            // label3
            // 
            this.label3.Location = new System.Drawing.Point(8, 44);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(64, 24);
            this.label3.TabIndex = 9;
            this.label3.Text = "User &pwd:";
            // 
            // txtUser
            // 
            this.txtUser.Location = new System.Drawing.Point(72, 20);
            this.txtUser.Name = "txtUser";
            this.txtUser.Size = new System.Drawing.Size(104, 20);
            this.txtUser.TabIndex = 8;
            this.toolTip.SetToolTip(this.txtUser, "SQL user name");
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(8, 20);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(64, 24);
            this.label2.TabIndex = 7;
            this.label2.Text = "&User name:";
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(8, 24);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(96, 24);
            this.label1.TabIndex = 2;
            this.label1.Text = "&Server name:";
            // 
            // grpSQLPath
            // 
            this.grpSQLPath.Controls.Add(this.btnDown);
            this.grpSQLPath.Controls.Add(this.btnUp);
            this.grpSQLPath.Controls.Add(this.btnClearFolders);
            this.grpSQLPath.Controls.Add(this.btnRemove);
            this.grpSQLPath.Controls.Add(this.lstFolders);
            this.grpSQLPath.Controls.Add(this.btnFolder);
            this.grpSQLPath.Controls.Add(this.chkSubFolders);
            this.grpSQLPath.Dock = System.Windows.Forms.DockStyle.Top;
            this.grpSQLPath.Enabled = false;
            this.grpSQLPath.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.grpSQLPath.Location = new System.Drawing.Point(0, 152);
            this.grpSQLPath.Name = "grpSQLPath";
            this.grpSQLPath.Size = new System.Drawing.Size(608, 128);
            this.grpSQLPath.TabIndex = 9;
            this.grpSQLPath.TabStop = false;
            this.grpSQLPath.Text = "SQL Script files path";
            // 
            // btnDown
            // 
            this.btnDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnDown.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnDown.Location = new System.Drawing.Point(560, 88);
            this.btnDown.Name = "btnDown";
            this.btnDown.Size = new System.Drawing.Size(40, 24);
            this.btnDown.TabIndex = 6;
            this.btnDown.Text = "Dwn";
            this.toolTip.SetToolTip(this.btnDown, "Move the selected folder down in the list");
            this.btnDown.Click += new System.EventHandler(this.btnDown_Click);
            // 
            // btnUp
            // 
            this.btnUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnUp.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnUp.Location = new System.Drawing.Point(520, 88);
            this.btnUp.Name = "btnUp";
            this.btnUp.Size = new System.Drawing.Size(40, 24);
            this.btnUp.TabIndex = 5;
            this.btnUp.Text = "Up";
            this.toolTip.SetToolTip(this.btnUp, "Move selected folder up in the list");
            this.btnUp.Click += new System.EventHandler(this.btnUp_Click);
            // 
            // btnClearFolders
            // 
            this.btnClearFolders.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnClearFolders.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnClearFolders.Location = new System.Drawing.Point(520, 64);
            this.btnClearFolders.Name = "btnClearFolders";
            this.btnClearFolders.Size = new System.Drawing.Size(80, 24);
            this.btnClearFolders.TabIndex = 4;
            this.btnClearFolders.Text = "Clear Folders";
            this.toolTip.SetToolTip(this.btnClearFolders, "Clear the folder list");
            this.btnClearFolders.Click += new System.EventHandler(this.btnClearFolders_Click);
            // 
            // btnRemove
            // 
            this.btnRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnRemove.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnRemove.Location = new System.Drawing.Point(520, 40);
            this.btnRemove.Name = "btnRemove";
            this.btnRemove.Size = new System.Drawing.Size(80, 24);
            this.btnRemove.TabIndex = 3;
            this.btnRemove.Text = "Remove";
            this.toolTip.SetToolTip(this.btnRemove, "Remove the selected folder from the list");
            this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
            // 
            // lstFolders
            // 
            this.lstFolders.AllowDrop = true;
            this.lstFolders.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.lstFolders.Location = new System.Drawing.Point(16, 40);
            this.lstFolders.Name = "lstFolders";
            this.lstFolders.Size = new System.Drawing.Size(496, 64);
            this.lstFolders.TabIndex = 2;
            this.lstFolders.DragDrop += new System.Windows.Forms.DragEventHandler(this.lstFolders_DragDrop);
            this.lstFolders.DragEnter += new System.Windows.Forms.DragEventHandler(this.lstFolders_DragEnter);
            // 
            // btnFolder
            // 
            this.btnFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnFolder.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnFolder.Location = new System.Drawing.Point(520, 16);
            this.btnFolder.Name = "btnFolder";
            this.btnFolder.Size = new System.Drawing.Size(80, 24);
            this.btnFolder.TabIndex = 0;
            this.btnFolder.Text = "Add";
            this.toolTip.SetToolTip(this.btnFolder, "Add a folder to the list");
            this.btnFolder.Click += new System.EventHandler(this.btnFolder_Click);
            // 
            // chkSubFolders
            // 
            this.chkSubFolders.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.chkSubFolders.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.chkSubFolders.Location = new System.Drawing.Point(19, 16);
            this.chkSubFolders.Name = "chkSubFolders";
            this.chkSubFolders.Size = new System.Drawing.Size(208, 24);
            this.chkSubFolders.TabIndex = 0;
            this.chkSubFolders.Text = "Check/Uncheck all folders in the list";
            this.toolTip.SetToolTip(this.chkSubFolders, "If a folder is checked the script files stored in subfolders are also executed");
            this.chkSubFolders.CheckedChanged += new System.EventHandler(this.chkSubFolders_CheckedChanged);
            // 
            // grpRun
            // 
            this.grpRun.Controls.Add(this.progressPane);
            this.grpRun.Controls.Add(this.btnRun);
            this.grpRun.Dock = System.Windows.Forms.DockStyle.Top;
            this.grpRun.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.grpRun.Location = new System.Drawing.Point(0, 280);
            this.grpRun.Name = "grpRun";
            this.grpRun.Size = new System.Drawing.Size(608, 48);
            this.grpRun.TabIndex = 10;
            this.grpRun.TabStop = false;
            this.grpRun.Text = "Run scripts";
            // 
            // progressPane
            // 
            this.progressPane.Controls.Add(this.btnAbort);
            this.progressPane.Controls.Add(this.progressBar);
            this.progressPane.Controls.Add(this.progressPict);
            this.progressPane.Location = new System.Drawing.Point(8, 14);
            this.progressPane.Name = "progressPane";
            this.progressPane.Size = new System.Drawing.Size(448, 30);
            this.progressPane.TabIndex = 2;
            this.progressPane.Visible = false;
            // 
            // btnAbort
            // 
            this.btnAbort.Location = new System.Drawing.Point(360, 3);
            this.btnAbort.Name = "btnAbort";
            this.btnAbort.Size = new System.Drawing.Size(80, 24);
            this.btnAbort.TabIndex = 2;
            this.btnAbort.Text = "Cancel";
            this.toolTip.SetToolTip(this.btnAbort, "Tries to stop the script processor");
            this.btnAbort.Click += new System.EventHandler(this.btnAbort_Click);
            // 
            // progressBar
            // 
            this.progressBar.Location = new System.Drawing.Point(32, 8);
            this.progressBar.Name = "progressBar";
            this.progressBar.Size = new System.Drawing.Size(320, 14);
            this.progressBar.TabIndex = 1;
            // 
            // progressPict
            // 
            this.progressPict.Image = ((System.Drawing.Image)(resources.GetObject("progressPict.Image")));
            this.progressPict.Location = new System.Drawing.Point(8, 4);
            this.progressPict.Name = "progressPict";
            this.progressPict.Size = new System.Drawing.Size(16, 16);
            this.progressPict.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.progressPict.TabIndex = 0;
            this.progressPict.TabStop = false;
            // 
            // btnRun
            // 
            this.btnRun.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.btnRun.Enabled = false;
            this.btnRun.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnRun.Location = new System.Drawing.Point(472, 16);
            this.btnRun.Name = "btnRun";
            this.btnRun.Size = new System.Drawing.Size(128, 24);
            this.btnRun.TabIndex = 1;
            this.btnRun.Text = "&Run Scripts";
            this.toolTip.SetToolTip(this.btnRun, "Run all the scripts");
            this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
            // 
            // grpScriptList
            // 
            this.grpScriptList.Controls.Add(this.btnClear);
            this.grpScriptList.Controls.Add(this.treeScripts);
            this.grpScriptList.Dock = System.Windows.Forms.DockStyle.Left;
            this.grpScriptList.Enabled = false;
            this.grpScriptList.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.grpScriptList.Location = new System.Drawing.Point(0, 328);
            this.grpScriptList.Name = "grpScriptList";
            this.grpScriptList.Size = new System.Drawing.Size(360, 133);
            this.grpScriptList.TabIndex = 13;
            this.grpScriptList.TabStop = false;
            this.grpScriptList.Text = "Script List";
            // 
            // btnClear
            // 
            this.btnClear.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.btnClear.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnClear.Location = new System.Drawing.Point(3, 106);
            this.btnClear.Name = "btnClear";
            this.btnClear.Size = new System.Drawing.Size(354, 24);
            this.btnClear.TabIndex = 13;
            this.btnClear.Text = "C&lear List";
            this.toolTip.SetToolTip(this.btnClear, "Clears script tree list");
            this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
            // 
            // treeScripts
            // 
            this.treeScripts.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.treeScripts.Location = new System.Drawing.Point(4, 16);
            this.treeScripts.Name = "treeScripts";
            this.treeScripts.Size = new System.Drawing.Size(350, 88);
            this.treeScripts.TabIndex = 12;
            this.treeScripts.DoubleClick += new System.EventHandler(this.treeScripts_DoubleClick);
            this.treeScripts.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeScripts_AfterSelect);
            // 
            // mnuMain
            // 
            this.mnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.mnuFile,
            this.mnuConnMgr,
            this.menuItem1});
            // 
            // mnuFile
            // 
            this.mnuFile.Index = 0;
            this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.mnuNew,
            this.mnuOpen,
            this.mnuSave,
            this.mnuSaveAs,
            this.menuItem6,
            this.mnuReset,
            this.menuItem3,
            this.mnuExit});
            this.mnuFile.Text = "&File";
            // 
            // mnuNew
            // 
            this.mnuNew.Index = 0;
            this.mnuNew.Shortcut = System.Windows.Forms.Shortcut.CtrlN;
            this.mnuNew.Text = "New";
            this.mnuNew.Click += new System.EventHandler(this.mnuNew_Click);
            // 
            // mnuOpen
            // 
            this.mnuOpen.Index = 1;
            this.mnuOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
            this.mnuOpen.Text = "&Open";
            this.mnuOpen.Click += new System.EventHandler(this.mnuOpen_Click);
            // 
            // mnuSave
            // 
            this.mnuSave.Enabled = false;
            this.mnuSave.Index = 2;
            this.mnuSave.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
            this.mnuSave.Text = "&Save";
            this.mnuSave.Click += new System.EventHandler(this.mnuSave_Click);
            // 
            // mnuSaveAs
            // 
            this.mnuSaveAs.Enabled = false;
            this.mnuSaveAs.Index = 3;
            this.mnuSaveAs.Text = "Save &As";
            this.mnuSaveAs.Click += new System.EventHandler(this.mnuSaveAs_Click);
            // 
            // menuItem6
            // 
            this.menuItem6.Index = 4;
            this.menuItem6.Text = "-";
            // 
            // mnuReset
            // 
            this.mnuReset.Enabled = false;
            this.mnuReset.Index = 5;
            this.mnuReset.Text = "&Reset Connection";
            this.mnuReset.Click += new System.EventHandler(this.mnuReset_Click);
            // 
            // menuItem3
            // 
            this.menuItem3.Index = 6;
            this.menuItem3.Text = "-";
            // 
            // mnuExit
            // 
            this.mnuExit.Index = 7;
            this.mnuExit.Text = "E&xit SQL Runner";
            this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click);
            // 
            // mnuConnMgr
            // 
            this.mnuConnMgr.Index = 1;
            this.mnuConnMgr.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.mnuOptimisticMgr,
            this.mnuPessimisticMgr,
            this.mnuStrictMgr,
            this.mnuCommitMgr,
            this.mnuRollbackMgr});
            this.mnuConnMgr.Text = "&Connection Manager";
            // 
            // mnuOptimisticMgr
            // 
            this.mnuOptimisticMgr.Index = 0;
            this.mnuOptimisticMgr.Text = "Optimistic";
            this.mnuOptimisticMgr.Click += new System.EventHandler(this.mnuOptimisticMgr_Click);
            // 
            // mnuPessimisticMgr
            // 
            this.mnuPessimisticMgr.Checked = true;
            this.mnuPessimisticMgr.Index = 1;
            this.mnuPessimisticMgr.Text = "Pessimistic";
            this.mnuPessimisticMgr.Click += new System.EventHandler(this.mnuPessimisticMgr_Click);
            // 
            // mnuStrictMgr
            // 
            this.mnuStrictMgr.Index = 2;
            this.mnuStrictMgr.Text = "Strict";
            this.mnuStrictMgr.Click += new System.EventHandler(this.mnuStrictMgr_Click);
            // 
            // mnuCommitMgr
            // 
            this.mnuCommitMgr.Index = 3;
            this.mnuCommitMgr.Text = "Commit Transaction";
            this.mnuCommitMgr.Click += new System.EventHandler(this.mnuCommitMgr_Click);
            // 
            // mnuRollbackMgr
            // 
            this.mnuRollbackMgr.Index = 4;
            this.mnuRollbackMgr.Text = "Rollback Transaction";
            this.mnuRollbackMgr.Click += new System.EventHandler(this.mnuRollbackMgr_Click);
            // 
            // menuItem1
            // 
            this.menuItem1.Index = 2;
            this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem2});
            this.menuItem1.Text = "&Help";
            // 
            // menuItem2
            // 
            this.menuItem2.Index = 0;
            this.menuItem2.Text = "&About";
            this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
            // 
            // toolTip
            // 
            this.toolTip.AutomaticDelay = 250;
            this.toolTip.AutoPopDelay = 2500;
            this.toolTip.InitialDelay = 250;
            this.toolTip.ReshowDelay = 250;
            // 
            // btnSQL
            // 
            this.btnSQL.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnSQL.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnSQL.Location = new System.Drawing.Point(216, 12);
            this.btnSQL.Name = "btnSQL";
            this.btnSQL.Size = new System.Drawing.Size(24, 24);
            this.btnSQL.TabIndex = 2;
            this.btnSQL.Text = "...";
            this.toolTip.SetToolTip(this.btnSQL, "Opens script in SQL Editor");
            this.btnSQL.Click += new System.EventHandler(this.btnSQL_Click);
            // 
            // grpEvent
            // 
            this.grpEvent.Controls.Add(this.btnSQL);
            this.grpEvent.Controls.Add(this.txtEventError);
            this.grpEvent.Controls.Add(this.txtEventName);
            this.grpEvent.Dock = System.Windows.Forms.DockStyle.Fill;
            this.grpEvent.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.grpEvent.Location = new System.Drawing.Point(360, 328);
            this.grpEvent.Name = "grpEvent";
            this.grpEvent.Size = new System.Drawing.Size(248, 133);
            this.grpEvent.TabIndex = 16;
            this.grpEvent.TabStop = false;
            this.grpEvent.Text = "Event Info";
            // 
            // txtEventError
            // 
            this.txtEventError.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtEventError.Location = new System.Drawing.Point(3, 40);
            this.txtEventError.Multiline = true;
            this.txtEventError.Name = "txtEventError";
            this.txtEventError.ReadOnly = true;
            this.txtEventError.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.txtEventError.Size = new System.Drawing.Size(242, 88);
            this.txtEventError.TabIndex = 1;
            // 
            // txtEventName
            // 
            this.txtEventName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtEventName.Location = new System.Drawing.Point(3, 16);
            this.txtEventName.Name = "txtEventName";
            this.txtEventName.ReadOnly = true;
            this.txtEventName.Size = new System.Drawing.Size(181, 20);
            this.txtEventName.TabIndex = 0;
            // 
            // bntSearch
            // 
            this.bntSearch.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.bntSearch.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.bntSearch.Location = new System.Drawing.Point(144, 57);
            this.bntSearch.Name = "bntSearch";
            this.bntSearch.Size = new System.Drawing.Size(128, 24);
            this.bntSearch.TabIndex = 11;
            this.bntSearch.Text = "&Search for SQL Servers";
            this.bntSearch.Click += new System.EventHandler(this.bntSearch_Click);
            // 
            // FormMain
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(608, 477);
            this.Controls.Add(this.grpEvent);
            this.Controls.Add(this.grpScriptList);
            this.Controls.Add(this.grpRun);
            this.Controls.Add(this.grpSQLPath);
            this.Controls.Add(this.grpDB);
            this.Controls.Add(this.stsBar);
            this.Controls.Add(this.grpLogin);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Menu = this.mnuMain;
            this.MinimumSize = new System.Drawing.Size(616, 504);
            this.Name = "FormMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "SQL Runner";
            this.Load += new System.EventHandler(this.frmMain_Load);
            this.Closing += new System.ComponentModel.CancelEventHandler(this.FormMain_Closing);
            this.grpDB.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.txtComment)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtConnMgrMode)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtTotal)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtTotalErrors)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtElapsedTime)).EndInit();
            this.grpLogin.ResumeLayout(false);
            this.grpUser.ResumeLayout(false);
            this.grpUser.PerformLayout();
            this.grpSQLPath.ResumeLayout(false);
            this.grpRun.ResumeLayout(false);
            this.progressPane.ResumeLayout(false);
            this.progressPane.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.progressPict)).EndInit();
            this.grpScriptList.ResumeLayout(false);
            this.grpEvent.ResumeLayout(false);
            this.grpEvent.PerformLayout();
            this.ResumeLayout(false);

		}
		#endregion
		#region Public Methods

		public void StartSplash()
		{
			// Instance a splash form given the image names
			splashForm = new frmSplash(this);

			// Run the form: Displaying the form is not enough
			Application.Run(splashForm);
            //splashForm.Show(this);
			
		}

		public FormMain()
		{
			Thread splashThread = new Thread(StartSplash);
			splashThread.Start();
			
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			// Tree initialization: Icons
			treeScripts.ImageList = new ImageList();
			treeScripts.ImageList.Images.Add(I_FOLDER);
			treeScripts.ImageList.Images.Add(I_FOLDER_C);
			treeScripts.ImageList.Images.Add(I_FILE);
			treeScripts.ImageList.Images.Add(I_FILE_C);
			treeScripts.ImageList.Images.Add(I_FOLDER_OPEN);
			treeScripts.ImageList.Images.Add(I_FOLDER_OPEN_C);
			timerExecution = new TimerExtended(components);
			timerExecution.Tick += timerExecution_Tick;
			// Check the version
			CheckForNewVersion();
			Thread.Sleep(2000);
		}

		public FormMain(FormMainController controller):this() {
			this.controller = controller;
			controller.FormInstance = this;
		}
		#endregion
		#region Protected Methods

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		// Close Splash screen is still open
		protected override void OnVisibleChanged(EventArgs e)
		{
			base.OnVisibleChanged (e);
			if (splashForm != null & Visible) CloseSplash();
		}

		#endregion
		#region Private Methods

		#region UI Methods

		#region Form events

		private void frmMain_Load(object sender, EventArgs e)
		{
			
			stsBar.ShowPanels = true;
			Text = "SQL Server Runner - [" + ProductVersion + "]";
			// Check for Properties file
			string filePath = ConfigurationSettings.AppSettings.Get("RunnerPropertiesFile").ToString();
			FileInfo file = new FileInfo(filePath);
			if (file.Exists) 
			{
				AppSettings = RunnerSettings.Deserialize(file.Name);
				RunnerProperties properties = AppSettings.FindSetPropertiesByKeyField(AppSettings.defaultProperties);
				RunnerProperty property = properties.FindProperty("servername");
				if ( property != null )
				{
					cmbServer.Text = property.value;
					if ( properties.FindProperty("uid") != null && 
						!properties.FindProperty("uid").value.Equals(String.Empty))
					{
						chkTrusted.Checked = false;
						txtUser.Text = properties.FindProperty("uid").value;
					}
					else
					{
						chkTrusted.Checked = true;
					}
				}
				foreach (RunnerProperties setProperties in AppSettings.Properties) {
					cmbServer.Items.Add(setProperties.FindProperty("servername").value);
				}
			}
			else
			{
				AppSettings = new RunnerSettings();
			}
			SetGroups();
		}

		private void FormMain_Closing(object sender, CancelEventArgs e)
		{
			if ( applicationStatus == Status.Executing | 
				applicationStatus == Status.Cancel )
			{
				DialogResult result = MessageBox.Show(
					"Some scripts are being processed at this moment, " + 
					"do you want to finish the application?",
					"Exit SQL Runner",
					MessageBoxButtons.YesNo,
					MessageBoxIcon.Hand);

				if ( result == DialogResult.No )
				{
					e.Cancel = true;
				}
				else
				{
					btnAbort_Click(this, new EventArgs());
					Thread.Sleep(5000);
					controller.AbortRunner();
				}
			}
		}

		#endregion
		#region Command Buttons

        private void bntSearch_Click(object sender, EventArgs e)
        {
            List<string> servers = ServiceContainer.SQLServerFinder.GetSQLServers();
            if (servers == null)
            {
                MessageBox.Show("No SQL Servers were found.");
                return;
            }
            frmServerSearch search = new frmServerSearch(servers);
            DialogResult result = search.ShowDialog(this);
            if (result != DialogResult.OK) return;
            if (!cmbServer.Items.Contains(search.Server))
            {
                cmbServer.Items.Add(search.Server);
            }
            cmbServer.Text = search.Server;
        }

		private void btnAbort_Click(object sender, EventArgs e)
		{
		    if (applicationStatus != Status.Executing) return;
		    setComment("Waiting for SQL Server to finish executing current script to close the connection to the server ... please wait");
		    controller.CancelRunner();
		    btnAbort.Enabled = false;
		}

		private void btnRun_Click(object sender, EventArgs e)
		{
			SQLProject project = controller.RefreshSQLProject(lstFolders, this);
			if ( project.Folders.Count == 0 ) return;
			string user = chkTrusted.Checked? "" : txtUser.Text;
			controller.
				WriteProperties(AppSettings, cmbServer.Text, cmbDatabases.Text, user);
			Cursor = Cursors.WaitCursor;
			ApplicationStatus = Status.Executing;
			prevFolderStatus = ProjectStatus;
			ProjectStatus = Status.Executing;
			totalCounter = 0;
			errorCounter = 0;
			updateCounters();
			controller.Project = project;
			progressBar.Maximum = controller.TotalFiles();
			controller.runScripts();
			ServiceContainer.Logger.LogMessage("btnRun - formMain-Run thread has started");
			Cursor = Cursors.Default;
		}

		private void btnConn_Click(object sender, EventArgs e)
		{
			Cursor = Cursors.WaitCursor;
			setComment("Connecting to [{0}] SQL Server, please wait ...", cmbServer.Text);
			try
			{
				controller.ConnectToSql(cmbDatabases, 
					cmbServer.Text, txtUser.Text, txtPwd.Text, chkTrusted.Checked, AppSettings.DefaultSetProperties());
				ApplicationStatus = Status.Connected;
				setComment("Connection was established to server [{0}], please select database", cmbServer.Text);
			}
			catch (Exception exception)
			{
				Regex expression = new Regex(@"(\[(\w*\s*)*\])+");
				string msg = expression.Replace(exception.Message, "");
				ServiceContainer.Logger.LogMessage(
					String.Format("Error openning connection: {0}", msg), MsgLevel.Error);
				MessageBox.Show(this,String.Format(
					"The following error took place when connecting to the [{0}] SQL Server: \n\n{1}"
					, cmbServer.Text, msg), "SQL Runner - Error openning connection");
				setComment("Idle, please connect to SQL Server","");
			}
			Cursor = Cursors.Default;
		}

		private void btOpenDB_Click(object sender, EventArgs e)
		{
			connectToDB(cmbDatabases.Text);
		}

		private void btnFolder_Click(object sender, EventArgs e)
		{
			RunnerProperties properties = AppSettings.DefaultSetProperties();
			RunnerProperty property = properties != null? properties.FindProperty("path") : null;
			DirectoryInfo aDir;
			if (property != null && property.value.Length > 0)
			{
				aDir = new DirectoryInfo(property.value);
				if (aDir.Exists) fBrowser.SelectedPath = property.value;
			}
			if (fBrowser.ShowDialog(this) == DialogResult.OK && fBrowser.SelectedPath.Length > 0)
			{
				aDir = new DirectoryInfo(fBrowser.SelectedPath);
				ArrayList folders = new ArrayList(1);
				folders.Add(aDir);
				controller.AddFolders(folders, lstFolders);
				if (lstFolders.Items.Count > 0) btnRun.Enabled = true;
				txtComment.Text = "Press button to start running scripts";
				if (property != null) property.value = fBrowser.SelectedPath;
				FormMainController.LastPath = fBrowser.SelectedPath;
			}
			else
			{
				if ( lstFolders.Items.Count == 0 )
				{
					btnRun.Enabled = false;
					txtComment.Text = "Select folder to run scripts from";
				}
			}
		}

		private void btnClear_Click(object sender, EventArgs e)
		{
			ServiceContainer.EventLogger.Reset();
			refreshTree();
		}

		private void btnSQL_Click(object sender, EventArgs e)
		{
			bool errorFlag = false;
			if (treeScripts.SelectedNode == null) return;
			if (treeScripts.SelectedNode.Tag == null) return;
			SQLUtil sqlApp = new SQLUtil();
			int version = ServiceContainer.SQLConnection.VersionMajor;
			string app = sqlApp.SqlApplicationFactory(version);
			
			string arg = sqlApp.SqlArgumentFactory(version, 
				new SQLArguments( cmbServer.Text, 
								  cmbDatabases.Text, 
								  txtUser.Text, 
								  txtPwd.Text, 
								  chkTrusted.Checked, 
								  ((IItemLog) treeScripts.SelectedNode.Tag).Path.FullPath() + @"\" + treeScripts.SelectedNode.Text));
				
			try
			{
				Process.Start(app, arg );
			}
			catch(Exception exp)
			{
				MessageBox.Show(this, String.Format("An error took place when SQL Query application was called: {0}", exp.Message));
				errorFlag = true;
			}

			if ( errorFlag )
			{
				openWithNotepad(((IItemLog) treeScripts.SelectedNode.Tag).Path.FullPath() 
					+ @"\" + treeScripts.SelectedNode.Text);
			}
		}

		private void btnRemove_Click(object sender, EventArgs e)
		{
			if (lstFolders.SelectedItem != null)
			{
				lstFolders.Items.Remove(lstFolders.SelectedItem);
				ProjectStatus = Status.Dirty;
			}
		}

		private void btnClearFolders_Click(object sender, EventArgs e)
		{
			lstFolders.Items.Clear();
		}

		private void btnUp_Click(object sender, EventArgs e)
		{
			if(lstFolders.SelectedItem != null && lstFolders.SelectedIndex > 0)
			{
				int index = lstFolders.SelectedIndex;
				object item = lstFolders.SelectedItem;
				lstFolders.Items.RemoveAt(index);
				index--;
				lstFolders.Items.Insert(index, item);
				lstFolders.SelectedIndex = index;
				ProjectStatus = Status.Dirty;
			}
		}

		private void btnDown_Click(object sender, EventArgs e)
		{
			if(lstFolders.SelectedItem != null && (lstFolders.SelectedIndex + 1) < lstFolders.Items.Count)
			{
				int index = lstFolders.SelectedIndex;
				object item = lstFolders.SelectedItem;
				lstFolders.Items.RemoveAt(index);
				index++;
				lstFolders.Items.Insert(index, item);
				lstFolders.SelectedIndex = index;
				ProjectStatus = Status.Dirty;
			}
		}

		#endregion
		#region Other Controls

		private void treeScripts_AfterSelect(object sender, TreeViewEventArgs e)
		{
			ServiceContainer.Logger.LogMessage("TreeScripts - After Select was started");
			if (treeScripts.SelectedNode != null)
			{
				if (treeScripts.SelectedNode.Tag != null)
				{
					IItemLog log = (IItemLog) treeScripts.SelectedNode.Tag;
					String[] strPhrases = log.Error.Split((char) 10);
					StringBuilder strBuilder = controller.ParseErrorMessage(strPhrases);
					txtEventError.Text = strBuilder.ToString();
					txtEventName.Text = log.Name;
				}
			}
			ServiceContainer.Logger.LogMessage("TreeScripts - After Select has finished");
		}

		private void treeScripts_DoubleClick(object sender, EventArgs e)
		{
			btnSQL_Click(sender, e);	
		}

		private void lstFolders_DragDrop(object sender, DragEventArgs e)
		{
			IFolderReader reader = ReaderFactory.GetReader(e.Data);
			ArrayList folders = reader.ReadFolders(e);
			controller.AddFolders(folders, lstFolders);
			if ( lstFolders.Items.Count > 0 ) btnRun.Enabled = true;
		}

		private void lstFolders_DragEnter(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.CommaSeparatedValue) |
				e.Data.GetDataPresent(DataFormats.FileDrop))
			{
				e.Effect = DragDropEffects.Copy;
			}
			else
			{
				e.Effect = DragDropEffects.None;
			}
		}

		#endregion
		#region Menus

		private void mnuReset_Click(object sender, EventArgs e){
			ServiceContainer.SQLConnection.Reset();
			ApplicationStatus = Status.Initial;
		}

		private void mnuExit_Click(object sender, EventArgs e){	
			Close();		
		}
		
		private void menuItem2_Click(object sender, EventArgs e){
			frmAbout aform = new frmAbout();
			aform.ShowDialog(this);
		}

		private void mnuOpen_Click(object sender, EventArgs e){
			CheckIfIsDirty(sender, e);
			openFile.CheckPathExists = true;
			openFile.Filter = "SQL Runner (*.sqlrunner)|*.sqlrunner";
			if (openFile.ShowDialog(this) == DialogResult.OK) {
				clearFolders();
				chkSubFolders.Checked = false;
				controller.OpenSQLProject(openFile.FileName, this);
				ProjectStatus = Status.Initial;
			}
		}

		private void RefreshWindowTitle() {
			Text = "SQL Server Runner - [" + 
				ProductVersion + "]";
			if (controller.Project != null)
			{
				Text +=  " - " + controller.Project.FileFullPath();
				if (ProjectStatus == Status.Dirty) 
				{
					Text += "*";
				}
			}
		}

		private void mnuSave_Click(object sender, EventArgs e){
			if (lstFolders.Items.Count == 0){
				MessageBox.Show("Please some folder/s before you try to save the project",
					"Save Project", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				return;
			}
			if (controller.Project.FileFullPath().Equals(string.Empty) ||
				!File.Exists(controller.Project.FileFullPath()) )
			{
				mnuSaveAs_Click(sender, e);
				return;
			}
			controller.RefreshSQLProject(lstFolders, this).Serialize(controller.Project.FileFullPath());
			ProjectStatus = Status.Initial;
		}

		private void mnuSaveAs_Click(object sender, EventArgs e){
			if (lstFolders.Items.Count == 0)
			{
				MessageBox.Show("Please some folder/s before you try to save the project",
					"Save Project", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				return;
			}
			saveFile.CheckPathExists = true;
			saveFile.AddExtension = true;
			saveFile.Filter = "SQL Runner (*.sqlrunner)|*.sqlrunner";
			if (saveFile.ShowDialog(this) == DialogResult.OK) 
			{
				controller.RefreshSQLProject(lstFolders, this).Serialize(saveFile.FileName);
				ProjectStatus = Status.Initial;
			}
		}
		
		private void mnuNew_Click(object sender, EventArgs e)
		{
			CheckIfIsDirty(sender, e);
			clearFolders();
			chkSubFolders.Checked = false;
			SQLProject proj = new SQLProject();
			proj.Extensions.Add("sql");
			controller.Project = proj;
			ProjectStatus = Status.Initial;
		}

		#endregion
		#region Check Boxes

		private void chkTrusted_CheckedChanged(object sender, EventArgs e)
		{
			grpUser.Enabled = !(chkTrusted.Checked);
		}

		private void chkSubFolders_CheckedChanged(object sender, EventArgs e)
		{
			for (int i=0; i < lstFolders.Items.Count; i++)
			{
				lstFolders.SetItemChecked(i, chkSubFolders.Checked);
				ProjectStatus = Status.Dirty;
			}
		}
		#endregion

		#endregion
		#region Internal Properties

		internal Status ApplicationStatus
		{
			get
			{
				return applicationStatus;
			}
			set
			{
				applicationStatus = value;
				applicationGroups.UpdateStatus(value);
			}
		}

		private Status ProjectStatus {
			get { return projectStatus; }
			set {
				prevFolderStatus = projectStatus;
				projectStatus = value;
				folderGroups.UpdateStatus(value);
				RefreshWindowTitle();
			}
		}

		public Status PrevFolderStatus {
			get { return prevFolderStatus; }
		}

	    public ConnectionMgrType ConnectionMgrMode
	    {
	        get { return _connMgrType; }
	    }

	    #endregion
		#region Helper Methods
		
		#region Internal Methods

		internal void increaseTotalCounter()
		{
			ServiceContainer.Logger.LogMessage("increaseTotalCounter was called");
			totalCounter++;
			updateCounters();
		}

		internal void increaseErrorCounter()
		{
			ServiceContainer.Logger.LogMessage("increaseErrorCounter was called");
			errorCounter++;
			updateCounters();
		}

		internal void addLog(IItemLog item)
		{
			ServiceContainer.Logger.LogMessage("AddLog method was called");
			logItem(item);
		}

        internal void changeAppStatus(Status status)
        {
            ApplicationStatus = status;  
        }

        internal void changeProjectStatus(Status status)
        {
            ProjectStatus = status;
        }

		internal void setComment(string format, params object[] args)
		{
			ServiceContainer.Logger.LogMessage("setComment method was called");
			txtComment.Text = String.Format(format, args);
		}
		
		internal void addFolder(string folder, bool isChecked) {
			lstFolders.Items.Add(folder, isChecked);
		}

		internal void clearFolders() {
			lstFolders.Items.Clear();
		}

		#endregion
		#region Private Methods

		private void SetGroups()
		{
			// Application groups
			GroupControls g = new GroupControls("Enabled", Status.Initial);
			g.AddControl(grpLogin);
			applicationGroups.AddGroup(g);
	
			g = new GroupControls("Enabled", Status.Connected);
			g.AddControl(grpDB);
			applicationGroups.AddGroup(g);
	
			g = new GroupControls("Enabled", Status.DBSelected);
			g.AddControl(btnRun);
			g.AddControl(grpEvent);
			g.AddControl(btnClear);
			g.AddControl(grpSQLPath);
			g.AddControl(mnuReset);
			applicationGroups.AddGroup(g);

            g = new GroupControls("Enabled", Status.DBSelected | Status.Initial | Status.Connected);
            g.AddControl(mnuConnMgr);
            applicationGroups.AddGroup(g);
	
			g = new GroupControls("Enabled", Status.DBSelected | Status.Executing);
			g.AddControl(grpScriptList);
			applicationGroups.AddGroup(g);
	
			g = new GroupControls("Visible", Status.Executing | Status.Cancel);
			g.AddControl(progressPane);
			applicationGroups.AddGroup(g);

			g = new GroupControls("Enabled", Status.Executing | Status.Cancel);
			g.AddControl(timerExecution);
			applicationGroups.AddGroup(g);

			g = new GroupControls("Enabled", Status.Executing);
			g.AddControl(btnAbort);
			applicationGroups.AddGroup(g);

			// Folder Status
			g = new GroupControls("Enabled", Status.Initial | Status.Dirty);
			g.AddControl(mnuOpen);
			g.AddControl(mnuSaveAs);
			g.AddControl(mnuNew);
			folderGroups.AddGroup(g);

			g = new GroupControls("Enabled", Status.Dirty);
			g.AddControl(mnuSave);
			folderGroups.AddGroup(g);
		}

		private void updateCounters()
		{
			ServiceContainer.Logger.LogMessage("updateCounters was called");
			progressBar.Value = totalCounter <= progressBar.Maximum ? 
				totalCounter : progressBar.Maximum;
			txtTotal.Text = "Scripts: " + totalCounter;
			txtTotalErrors.Text = "Errors: " + errorCounter;
		}

		private void refreshTree()
		{
			treeScripts.Nodes.Clear();
			txtEventName.Text ="";
			txtEventError.Text ="";
		}

		private void logItem(IItemLog log)
		{
			//log.Path.RefreshNextNode(null);
			TreeNode parentNode = 
				controller.GetParentNode(treeScripts.Nodes, log.Path.FirstNode());
			if ( parentNode.ImageIndex == -1 )
			{
				parentNode.ImageIndex = (int) IconList.Folder;
				parentNode.SelectedImageIndex = (int) IconList.Folder_Open;
			}
			TreeNode node = new TreeNode(log.Name);
			node.Tag = log;
			node.ImageIndex = (int) IconList.File;
			node.SelectedImageIndex = node.ImageIndex;
			parentNode.Nodes.Add(node);
			if (log.Type == EventType.ERROR)
				errorInNode(node);
		}
		
		private void errorInNode(TreeNode node)
		{
			node.ForeColor = Color.Red;
			if (node.Tag == null)
			{
				node.ImageIndex = (int) IconList.Folder_Cancelled;
				node.SelectedImageIndex = (int) IconList.Folder_Open_Cancelled;
			}
			else
			{
				node.ImageIndex = (int) IconList.File_Cancelled;
				node.SelectedImageIndex = node.ImageIndex;
			}
			if (node.Parent != null) errorInNode(node.Parent);
		}

		private void connectToDB(string dbName)
		{
			setComment("connecting to {0} database", dbName);
			ServiceContainer.SQLConnection.GetDatabase(dbName);
			setComment("Select folder with scripts to run","");
			ApplicationStatus = Status.DBSelected;
		}

		private void openWithNotepad(string path)
		{

			DialogResult result = MessageBox.Show("Do you want to open the script in notepad?", "Opening script", 
				MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
			if ( result == DialogResult.Yes )
			{
			    string app = "notepad.exe";
				string arg = path;
				try
				{
					Process.Start(app, arg);
				}
				catch (Exception exp)
				{
					MessageBox.Show(this, String.Format("An error took place when the notepad was called: {0}", exp.Message));
				}
			}
		}

		private void timerExecution_Tick(object sender, EventArgs e)
		{
			txtElapsedTime.Text = String.Format("Elapsed Time: {0}",
				timerExecution.ElapsedTime);
		}

		private void CloseSplash()
		{
			if ( splashForm == null ) return;
			// Shut down the splash screen
			splashForm.Invoke(new EventHandler(splashForm.KillMe));
			splashForm.Dispose();
			splashForm = null;
		}

		private void CheckIfIsDirty(object sender, EventArgs e) 
		{
			if (ProjectStatus == Status.Dirty &&
				MessageBox.Show("Do you want to save project changes?", "Save Project", 
				MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes) 
			{
				mnuSave_Click(sender, e);
			}
		}

		#endregion

		#endregion
		#region Check For New Version
		
		private void CheckForNewVersion()
		{
			bool flag = bool.Parse(ConfigurationSettings.AppSettings.Get("CheckForNewVersion"));
			if ( !flag ) return;
			URLChecker checker = new URLChecker();
			CheckVersionHandler checkerCall = new CheckVersionHandler(checker.CheckVersion);
			checkerCall.BeginInvoke(
				ConfigurationSettings.AppSettings.Get("NewVersionUrl"), 
				Assembly.GetExecutingAssembly().GetName().Version, 
				new AsyncCallback(AsyncCheckVersion), null);
		}

		private void AsyncCheckVersion(IAsyncResult receipt)
		{
			AsyncResult result = (AsyncResult)receipt;
			//  retrieve the calling delegate
			CheckVersionHandler checkerCall = (CheckVersionHandler)result.AsyncDelegate;
			//  Retrieve our results; this is guaranteed not to block, as the async op is complete
			SQLRunnerVersion webVersion = checkerCall.EndInvoke(receipt);
			if ( webVersion != null )
			{
				bool flag = webVersion.Version.CompareTo(
								AppVersion.ConvertFromSystemVersion(
									Assembly.GetExecutingAssembly().GetName().Version)) > 0;
				if ( !flag ) return;
				checkVersionForm = 
					new frmCheckNewVersion(
					webVersion.MsiUrl, 
					AppVersion.TransforToSystemVersion(webVersion.Version),
					webVersion.LinkText);
				Application.Run(checkVersionForm);
			}
		}
		
		#endregion
        #region "Connection Manager Menus"

        private ConnectionMgrType _connMgrType = ConnectionMgrType.PessimistConnMgr;
        private void mnuPessimisticMgr_Click(object sender, EventArgs e)
        {
            setConnMgr(mnuPessimisticMgr, ConnectionMgrType.PessimistConnMgr);

        }
        private void setConnMgr(MenuItem menuItem, ConnectionMgrType mode)
        {
            mnuPessimisticMgr.Checked = false;
            mnuOptimisticMgr.Checked = false;
            mnuRollbackMgr.Checked = false;
            mnuStrictMgr.Checked = false;
            mnuCommitMgr.Checked = false;
            menuItem.Checked = true;
            _connMgrType = mode;
            string modeDesc = Enum.GetName(typeof (ConnectionMgrType), mode);
            modeDesc = modeDesc.Substring(0, modeDesc.IndexOf("ConnMgr"));
            txtConnMgrMode.Text = "Connection Mgr: " + modeDesc;
        }

        private void mnuOptimisticMgr_Click(object sender, EventArgs e)
        {
            setConnMgr(mnuOptimisticMgr, ConnectionMgrType.OptimisticConnMgr);
        }

        private void mnuStrictMgr_Click(object sender, EventArgs e)
        {
            setConnMgr(mnuStrictMgr, ConnectionMgrType.StrictConnMgr);
        }

        private void mnuCommitMgr_Click(object sender, EventArgs e)
        {
            setConnMgr(mnuCommitMgr, ConnectionMgrType.CommitTransactionConnMgr);
        }

        private void mnuRollbackMgr_Click(object sender, EventArgs e)
        {
            setConnMgr(mnuRollbackMgr, ConnectionMgrType.RollbackTransactionConnMgr);
        }
        #endregion

        #endregion
    }
}
